package com.coder.algorithm.offer_2;

/**
 * 翻转单词顺序
 *
 * @author yuhushuan
 * @date 2020/7/1 23:31
 */
public class _58_1_ReverseWordsInSentence {

    private static String reverseSentence(String data) {
        if (data == null) {
            return null;
        }
        char[] result = data.toCharArray();
        int length = result.length;
        int start = 0;
        int end = length - 1;

        // 翻转整个句子
        reverse(result, start, end);
        end = 0;
        while (end < length) {
            if (result[end] == ' ') {
                reverse(result, start, end - 1);
                end++;
                start = end;
            }
            if (end == length - 1) {
                reverse(result, start, end);
                end++;
            } else {
                end++;
            }
        }
        return new String(result);
    }

    private static void reverse(char[] data, int start, int end) {
        if (data == null) {
            return;
        }
        while (start < end) {
            char temp = data[start];
            data[start] = data[end];
            data[end] = temp;
            start++;
            end--;
        }
    }


    private static String reverseWords(String sentence) {
        if (sentence == null) {
            return null;
        }
        if (sentence.length() <= 1) {
            return sentence;
        }
        int length = sentence.length();
        char[] result = new char[length];
        int start = 0;
        int end = length - 1;
        for (int i = sentence.length() - 1; i >= 0; --i) {
            if (sentence.charAt(i) == ' ') {
                for (int j = i + 1; j <= end; ++j) {
                    result[start++] = sentence.charAt(j);
                }
                result[start++] = sentence.charAt(i);
                end = i - 1;
            }
        }
        for (int j = 0; j <= end; ++j) {
            result[start++] = sentence.charAt(j);
        }
        return new String(result);
    }

    public static void main(String[] args) {
        // 功能测试
        print("I am a student.");
        print("student.");
        print(" student");

        // 特殊输入测试
        print(null);
        print("");
        print("     ");
    }

    private static void print(String str) {
        System.out.println("英文句子：\n" + str);
        System.out.println("翻转单词顺序后直接翻转：\n" + reverseWords(str));
        System.out.println("翻转单词顺序后两次翻转：\n" + reverseSentence(str) + '\n');

    }
}
